require 'rake'
require 'rake/testtask'
require 'tempfile'


task :default => [:java_compile,:test]

def java_classpath_arg #myriad of ways to discover JRuby classpath
  begin
    require 'java' # already running in a JRuby JVM
    jruby_cpath = Java::java.lang.System.getProperty('java.class.path')
  rescue LoadError
  end
  unless jruby_cpath
    jruby_cpath = ENV['JRUBY_PARENT_CLASSPATH'] || ENV['JRUBY_HOME'] &&
      FileList["#{ENV['JRUBY_HOME']}/lib/*.jar"].join(File::PATH_SEPARATOR)
  end
  local_libraries = (FileList["lib/*.jar"]+%w(cfg test)).join(File::PATH_SEPARATOR)
  cpath_arg = jruby_cpath ? "-cp #{jruby_cpath}#{File::PATH_SEPARATOR}#{local_libraries}" : "-cp #{local_libraries}"
end

desc "Compile the native Java code."
task :java_compile do
  mkdir_p "pkg/classes"
  sh "javac -d pkg/classes #{java_classpath_arg} #{FileList['src/java/**/*.java'].join(' ')}"
  Tempfile.open("manifest","w") do |f|
    f.puts "Manifest-Version: 1.0"
    f.puts "Built-By: someone"
    f.puts "Class-Path: #{FileList["lib/*.jar"].map{|s| s[4..-1]}.join(" ")}"
    f.flush
    sh "jar cfm lib/ActiveHibernateInternal.jar #{f.path} -C pkg/classes ."
  end
end
file "lib/ActiveHibernateInternal.jar" => :java_compile

desc "Run ActiveHibernate tests"
task :test => [:test_hsqldb]

Rake::TestTask.new(:test_hsqldb) do |t|
  t.test_files = FileList['test/**/*_test.rb']
  t.libs << 'test'
end
